<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-04-30
// +—————————————————————————————————————————————————————————————————————

session_start();
class Model_Video extends PhalApi_Model_NotORM {
	/* 发布视频 */
	public function setVideo($data,$music_id) {
		$uid=$data['uid'];

		//获取后台配置的初始曝光值
		$configPri=getConfigPri();

		if($configPri['video_audit_switch']==0){
			$data['status']=1;
		}

		$data['thumb']=setCloudType($data['thumb']);
		$data['thumb_s']=setCloudType($data['thumb_s']);
		$data['href']=setCloudType($data['href']);
		$data['href_w']=setCloudType($data['href_w']);

		$result= DI()->notorm->user_video->insert($data);

		if($music_id>0){ //更新背景音乐被使用次数
			DI()->notorm->user_music
            ->where("id = '{$music_id}'")
		 	->update( array('use_nums' => new NotORM_Literal("use_nums + 1") ) );
		}
		
		return $result;
	}

	/* 评论/回复 */
    public function setComment($data) {
    	$videoid=$data['videoid'];

		
        $res=DI()->notorm->user_video_comments->insert($data);


        if(!$res){
        	return 1001;
        }

        /* 更新 视频 */
		DI()->notorm->user_video
            ->where("id = '{$videoid}'")
		 	->update( array('comments' => new NotORM_Literal("comments + 1") ) );

			
		$videoinfo=DI()->notorm->user_video
					->select("comments")
					->where('id=?',$videoid)
					->fetchOne();
					
		$count=DI()->notorm->user_video_comments
					->where("commentid='{$data['commentid']}'")
					->count();

		

		$rs=array(
			'comments'=>$videoinfo['comments'],
			'replys'=>$count,
		);


		//他人直接对视频进行的评论，向评论信息表中写入记录

		if($data['uid']!=$data['touid']){

			$data2=array("uid"=>$data['uid'],"touid"=>$data['touid'],"videoid"=>$data['videoid'],"content"=>$data['content'],"addtime"=>time());
			DI()->notorm->user_video_comments_messages->insert($data2);
			//$data['touid']为视频发布者ID或评论者ID
			
			
		}

		
		

		return $rs;	
    }			

	/* 阅读 */
	public function addView($uid,$videoid){
        /* 观看记录 */
        $nowtime=time();
        $ifok=DI()->notorm->user_video_view
				->where('uid=? and videoid=?',$uid,$videoid)
				->update(['addtime'=>$nowtime]);


        if(!$ifok){
            DI()->notorm->user_video_view
						->insert(array("uid"=>$uid,"videoid"=>$videoid,"addtime"=>$nowtime ));
        }
        
        /* 减少上热门 */
        DI()->notorm->user_video
				->where("id = ? and p_expire>? and p_nums>=1",$videoid,$nowtime)
				->update( array('p_nums' => new NotORM_Literal("p_nums - 1") ) );

				
	

		DI()->notorm->user_video
				->where("id = '{$videoid}'")
				->update( array('views' => new NotORM_Literal("views + 1") ) );

		return 0;
	}
	/* 点赞 */
	public function addLike($uid,$videoid){
		$rs=array(
			'islike'=>'0',
			'likes'=>'0',
		);
		$video=DI()->notorm->user_video
				->select("likes,uid,thumb")
				->where("id = '{$videoid}'")
				->fetchOne();

		if(!$video){
			return 1001;
		}
		if($video['uid']==$uid){
			return 1002;//不能给自己点赞
		}
		$like=DI()->notorm->user_video_like
						->select("id")
						->where("uid='{$uid}' and videoid='{$videoid}'")
						->fetchOne();
		if($like){
			DI()->notorm->user_video_like
						->where("uid='{$uid}' and videoid='{$videoid}'")
						->delete();
			
			DI()->notorm->user_video
				->where("id = '{$videoid}' and likes>0")
				->update( array('likes' => new NotORM_Literal("likes - 1") ) );
			$rs['islike']='0';
		}else{
			DI()->notorm->user_video_like
						->insert(array("uid"=>$uid,"videoid"=>$videoid,"addtime"=>time() ));
			
			DI()->notorm->user_video
				->where("id = '{$videoid}'")
				->update( array('likes' => new NotORM_Literal("likes + 1") ) );
			$rs['islike']='1';
		}	
		
		$video=DI()->notorm->user_video
				->select("likes,uid,thumb")
				->where("id = '{$videoid}'")
				->fetchOne();
				
		$rs['likes']=NumberFormat($video['likes']);
		

		return $rs; 		
	}
 


	/* 分享 */
	public function addShare($uid,$videoid){

		
		$rs=array(
			'isshare'=>'0',
			'shares'=>'0',
		);
		DI()->notorm->user_video
			->where("id = '{$videoid}'")
			->update( array('shares' => new NotORM_Literal("shares + 1") ) );
		$rs['isshare']='1';

		
		$video=DI()->notorm->user_video
				->select("shares")
				->where("id = '{$videoid}'")
				->fetchOne();
		$rs['shares']=NumberFormat($video['shares']);
		
		return $rs; 		
	}




	/* 评论/回复 点赞 */
	public function addCommentLike($uid,$commentid){
		$rs=array(
			'islike'=>'0',
			'likes'=>'0',
		);

		//根据commentid获取对应的评论信息
		$commentinfo=DI()->notorm->user_video_comments
			->where("id='{$commentid}'")
			->fetchOne();

		if(!$commentinfo){
			return 1001;
		}

		$like=DI()->notorm->user_video_comments_like
			->select("id")
			->where("uid='{$uid}' and commentid='{$commentid}'")
			->fetchOne();

		if($like){
			DI()->notorm->user_video_comments_like
						->where("uid='{$uid}' and commentid='{$commentid}'")
						->delete();
			
			DI()->notorm->user_video_comments
				->where("id = '{$commentid}' and likes>0")
				->update( array('likes' => new NotORM_Literal("likes - 1") ) );
			$rs['islike']='0';

		}else{
			DI()->notorm->user_video_comments_like
						->insert(array("uid"=>$uid,"commentid"=>$commentid,"addtime"=>time(),"touid"=>$commentinfo['uid'],"videoid"=>$commentinfo['videoid'] ));
			
			DI()->notorm->user_video_comments
				->where("id = '{$commentid}'")
				->update( array('likes' => new NotORM_Literal("likes + 1") ) );
			$rs['islike']='1';
		}	
		
		$video=DI()->notorm->user_video_comments
				->select("likes")
				->where("id = '{$commentid}'")
				->fetchOne();

		//获取视频信息
		$videoinfo=DI()->notorm->user_video->select("thumb")->where("id='{$commentinfo['videoid']}'")->fetchOne();

		$rs['likes']=$video['likes'];

		return $rs; 		
	}
	
	/* 热门视频 */
	public function getVideoList($uid,$p){


		$nums=20;
		$start=($p-1)*$nums;

		$videoids_s='';
		$where="isdel=0 and status=1";  //上架且审核通过
		
		$video=DI()->notorm->user_video
				->select("*")
				->where($where)
				->order("RAND()")
				->limit($start,$nums)
				->fetchAll();

		//敏感词树        
        $tree=trieTreeBasic();

        foreach($video as $k=>$v){
            $v=handleVideo($uid,$v,$tree);
            
            $video[$k]=$v;
        }
        

		return $video;
	}

		
	
	/* 视频详情 */
	public function getVideo($uid,$videoid){
		$video=DI()->notorm->user_video
					->select("*")
					->where("id = {$videoid} and status=1 ")
					->fetchOne();
		if(!$video){
			return 1000;
		}

		//敏感词树        
        $tree=trieTreeBasic();		
		
        $video=handleVideo($uid,$video,$tree);
        
		return 	$video;
	}
	
	/* 评论列表 */
	public function getComments($uid,$videoid,$p){
		$nums=20;
		$start=($p-1)*$nums;
		$comments=DI()->notorm->user_video_comments
					->select("*")
					->where("videoid='{$videoid}' and parentid='0'")
					->order("addtime desc")
					->limit($start,$nums)
					->fetchAll();

		//敏感词树        
        $tree=trieTreeBasic();

		foreach($comments as $k=>$v){
			$comments[$k]['userinfo']=getUserInfo($v['uid'],$tree);				
			$comments[$k]['datetime']=datetime($v['addtime']);	
			$comments[$k]['likes']=NumberFormat($v['likes']);	

			if($uid){
				$comments[$k]['islike']=(string)$this->ifCommentLike($uid,$v['id']);	
			}else{
				$comments[$k]['islike']='0';	
			}
			
			if($v['touid']>0){
				$touserinfo=getUserInfo($v['touid'],$tree);
			}
			if(!$touserinfo){
				$touserinfo=(object)array();
				$comments[$k]['touid']='0';
			}
			$comments[$k]['touserinfo']=$touserinfo;

			$count=DI()->notorm->user_video_comments
					->where("commentid='{$v['id']}'")
					->count();
			$comments[$k]['replys']=$count;
			$comments[$k]['content']=eachReplaceSensitiveWords($tree,$v['content']);

			/* 回复 */
            $reply=DI()->notorm->user_video_comments
					->select("*")
					->where("commentid='{$v['id']}'")
					->order("addtime desc")
					->limit(0,1)
					->fetchAll();

			foreach($reply as $k1=>$v1){
                
                $v1['userinfo']=getUserInfo($v1['uid'],$tree);				
                $v1['datetime']=datetime($v1['addtime']);	
                $v1['likes']=NumberFormat($v1['likes']);	
                $v1['islike']=(string)$this->ifCommentLike($uid,$v1['id']);
                if($v1['touid']>0){
                    $touserinfo=getUserInfo($v1['touid'],$tree);
                }
                if(!$touserinfo){
                    $touserinfo=(object)array();
                    $v1['touid']='0';
                }
                
                if($v1['parentid']>0 && $v1['parentid']!=$v['id']){
                    $tocommentinfo=DI()->notorm->user_video_comments
                        ->select("content,at_info")
                        ->where("id='{$v1['parentid']}'")
                        ->fetchOne();
                }else{
                    $tocommentinfo=(object)array();
                    $touserinfo=(object)array();
                    $v1['touid']='0';
                }
                $v1['touserinfo']=$touserinfo;
                $v1['tocommentinfo']=$tocommentinfo;
                $v1['content']=eachReplaceSensitiveWords($tree,$v1['content']);


                $reply[$k1]=$v1;
            }

			$comments[$k]['replylist']=$reply;
		}
		
		$commentnum=DI()->notorm->user_video_comments
					->where("videoid='{$videoid}'")
					->count();
		
		$rs=array(
			"comments"=>$commentnum,
			"commentlist"=>$comments,
		);
		
		return $rs;
	}

	/* 回复列表 */
	public function getReplys($uid,$commentid,$last_replyid,$p){

		if($last_replyid==0){ //获取回复列表里最新的一条

			$comment=DI()->notorm->user_video_comments
				->select("*")
				->where("commentid='{$commentid}'")
				->order("addtime desc")
				->fetchOne();

			$comments[]=$comment;

		}else{
			if($p<1){
				$p=1;
			}


			//第一页获取2条数据，从第二页开始每页获取10条数据
			$nums=10;
			if($p==1){
				$nums=2;
			}

			$start=0;
			$comments=DI()->notorm->user_video_comments
				->select("*")
				->where("commentid='{$commentid}' and id< '{$last_replyid}'")
				->order("addtime desc")
				->limit($start,$nums)
				->fetchAll();

		}

		//敏感词树        
        $tree=trieTreeBasic();

		foreach($comments as $k=>$v){
			$comments[$k]['userinfo']=getUserInfo($v['uid'],$tree);				
			$comments[$k]['datetime']=datetime($v['addtime']);	
			$comments[$k]['likes']=NumberFormat($v['likes']);	
			$comments[$k]['islike']=(string)$this->ifCommentLike($uid,$v['id']);
			if($v['touid']>0){
				$touserinfo=getUserInfo($v['touid'],$tree);
			}
			if(!$touserinfo){
				$touserinfo=(object)array();
				$comments[$k]['touid']='0';
			}


			if($v['parentid']>0 && $v['parentid']!=$commentid){
				$tocommentinfo=DI()->notorm->user_video_comments
					->select("content,at_info")
					->where("id='{$v['parentid']}'")
					->fetchOne();
			}else{

				$tocommentinfo=(object)array();
				$touserinfo=(object)array();
				$comments[$k]['touid']='0';

			}

			$comments[$k]['touserinfo']=$touserinfo;
			$comments[$k]['tocommentinfo']=$tocommentinfo;
			$comments[$k]['content']=eachReplaceSensitiveWords($tree,$v['content']);


		}

		//该评论下的总回复数
		$count=DI()->notorm->user_video_comments
			->where("commentid='{$commentid}'")
			->count();

		$res['lists']=$comments;
		$res['replys']=$count;
		
		return $res;


	}
	
	/*删除评论 删除子级评论*/
	public function delComments($uid,$videoid,$commentid,$commentuid) {
       $result=DI()->notorm->user_video
					->select("uid")
					->where("id='{$videoid}'")
					->fetchOne();	
					
		if(!$result){
			return 1001;
		}			
		
		
		if($uid!=$commentuid){
			if($uid!=$result['uid']){
				return 1002;
			}
		}
			
		
		
		// 删除 评论记录
		DI()->notorm->user_video_comments
					->where("id='{$commentid}'")
					->delete(); 
		//删除视频评论喜欢
		DI()->notorm->user_video_comments_like
					->where("commentid='{$commentid}'")
					->delete(); 
		/* 更新 视频 */
		DI()->notorm->user_video
            ->where("id = '{$videoid}' and comments>0")
		 	->update( array('comments' => new NotORM_Literal("comments - 1") ) );
		
		
		//删除相关的子级评论
		$lists=DI()->notorm->user_video_comments
				->select("*")
				->where("commentid='{$commentid}' or parentid='{$commentid}'")
				->fetchAll();
		foreach($lists as $k=>$v){
			//删除 评论记录
			DI()->notorm->user_video_comments
						->where("id='{$v['id']}'")
						->delete(); 
			//删除视频评论喜欢
			DI()->notorm->user_video_comments_like
						->where("commentid='{$v['id']}'")
						->delete(); 
						
			/* 更新 视频 */
			DI()->notorm->user_video
				->where("id = '{$v['videoid']}' and comments>0")
				->update( array('comments' => new NotORM_Literal("comments - 1") ) );
		}
			
		
						
		return 0;

    }

	
	
	
	/* 评论/回复 是否点赞 */
	public function ifCommentLike($uid,$commentid){
		$like=DI()->notorm->user_video_comments_like
				->select("id")
				->where("uid='{$uid}' and commentid='{$commentid}'")
				->fetchOne();
		if($like){
			return 1;
		}else{
			return 0;
		}	
	}
	
	/* 我的视频 */
	public function getMyVideo($uid,$p){
		$nums=20;
		$start=($p-1)*$nums;
		
		$video=DI()->notorm->user_video
				->select("*")
				->where('uid=?  and status=1',$uid)
				->order("addtime desc")
				->limit($start,$nums)
				->fetchAll();
		
		//敏感词树        
        $tree=trieTreeBasic();

        foreach($video as $k=>$v){
            $v=handleVideo($uid,$v,$tree);
            
            $video[$k]=$v;
        }

		return $video;
	} 	
	/* 删除视频 */
	public function del($uid,$videoid){
		
		$result=DI()->notorm->user_video
					->select("*")
					->where("id='{$videoid}' and uid='{$uid}'")
					->fetchOne();	
		if($result){





			//将评论信息列表的状态更改	

			DI()->notorm->user_video_comments_messages
				->where("videoid='{$videoid}'")
				->update(array("status"=>0));

			//将喜欢的视频列表状态修改
			DI()->notorm->user_video_like
				->where("videoid='{$videoid}'")
				->update(array("status"=>0));
                
            //将喜欢的视频列表状态修改
			DI()->notorm->user_video_view
				->where("videoid='{$videoid}'")
				->update(array("status"=>0));	

			DI()->notorm->user_video
				->where("id='{$videoid}'")
				->update( array( 'isdel'=>1 ) );



		}				
		return 0;
	}	

	/* 个人主页视频 */
	public function getHomeVideo($uid,$touid,$p){
		$nums=20;
		$start=($p-1)*$nums;
		
		
		if($uid==$touid){  //自己的视频（需要返回视频的状态前台显示）
			$where=" uid={$uid} and isdel='0' and status=1";
		}else{  //访问其他人的主页视频
            


			$where=" uid={$touid} and isdel='0' and status=1";
		}
		
		
		$video=DI()->notorm->user_video
				->select("*")
				->where($where)
				->order("addtime desc")
				->limit($start,$nums)
				->fetchAll();

		//敏感词树        
        $tree=trieTreeBasic();

		foreach($video as $k=>$v){
            $v=handleVideo($uid,$v,$tree);
            
            $video[$k]=$v;
        }

		return $video;
		
	}
	/* 举报 */
	public function report($data) {
		
		$video=DI()->notorm->user_video
					->select("uid")
					->where("id='{$data['videoid']}' and status=1")
					->fetchOne();

		if(!$video){
			return 1000;
		}
		
		$data['touid']=$video['uid'];
					
		$result= DI()->notorm->user_video_report->insert($data);
		return 0;
	}


	public function getRecommendVideos($uid,$p,$isstart,$mobileid){
		$pnums=20;
		$start=($p-1)*$pnums;


		$nowtime=time();
		$configPri=getConfigPri();
		if($p==1){
			if($uid>0){
				DI()->redis -> del('readvideo_'.$uid);
			}else{
				DI()->redis -> del('readvideo_'.$mobileid);
			}
		}

		//去除看过的视频
		$where=array();
		if($uid>0){
			$readLists=DI()->redis -> Get('readvideo_'.$uid);
		}else{
			$readLists=DI()->redis -> Get('readvideo_'.$mobileid);
		}
		
		if($readLists){
			$where=json_decode($readLists,true);
		}

		$info=DI()->notorm->user_video
			->where("isdel=0 and status=1")
			->where('not id',$where)
			->order("rand()")
			->limit($pnums)
			->fetchAll();
		$where1=array();
		foreach ($info as $k => $v) {
			if(!in_array($v['id'],$where)){
				$where1[]=$v['id'];
			}
		}

		//将两数组合并
		$where2=array_merge($where,$where1);

		if($uid>0){
			DI()->redis -> set('readvideo_'.$uid,json_encode($where2));
		}else{
			DI()->redis -> set('readvideo_'.$mobileid,json_encode($where2));
		}
		
		if(!$info){
			return 1001;
		}

		$videoCount=count($info);
		//敏感词树        
        $tree=trieTreeBasic();

        foreach($info as $k=>$v){
            $v=handleVideo($uid,$v,$tree);
            
            $info[$k]=$v;
        }

		return $info;
	}

	
	

	/* 举报分类列表 */
	public function getReportContentlist() {
		
		$reportlist=DI()->notorm->user_video_report_classify
					->select("*")
					->order("orderno asc")
					->fetchAll();
		if(!$reportlist){
			return 1001;
		}

		//添加固定项 其他
		$reportlist[]=array(
			'id'=>'-1',
			'orderno'=>'1000',
			'name'=>'其他',
			'addtime'=>'1589872429'
		);

		
		return $reportlist;
		
	}

	/*更新视频看完次数*/
	public function setConversion($videoid){

		//更新视频看完次数
		$res=DI()->notorm->user_video
				->where("id = '{$videoid}' and status=1")
				->update( array('watch_ok' => new NotORM_Literal("watch_ok + 1") ) );

		return 1;
	}
    
    /* 标签下视频列表 */
    public function getLabelVideoList($uid,$labelid,$p){
        
        if($p<1){
            $p=1;
        }
        
        $nums=50;
        $start=($p-1)*$nums;
        
        
        $list=DI()->notorm->user_video
                ->select("*")
                ->where('labelid=? and status=1',$labelid)
                ->order("id desc")
                ->limit($start,$nums)
                ->fetchAll();

        //敏感词树        
        $tree=trieTreeBasic();
                
        foreach($list as $k=>$v){
            $v=handleVideo($uid,$v,$tree);
            $list[$k]=$v;
        }
                
        return $list;
    }



    //根据音乐id获取同类型视频列表
    public function getVideoListByMusic($uid,$musicid,$p){
    	if($p<1){
			$p=1;
		}
		$where="isdel=0 and status=1";
		$pnums=20;
		if($p!=1){
			$endtime=$_SESSION['music_video_endtime'];
			if($endtime){
				$where.=" and addtime<{$endtime}";
			}
		}

		$list=DI()->notorm->user_video
			->where("music_id=?",$musicid)
			->where($where)
			->order("addtime desc")
			->limit($pnums)
			->fetchAll();


		//敏感词树        
        $tree=trieTreeBasic();
                
        foreach($list as $k=>$v){
            $v=handleVideo($uid,$v,$tree);
            $list[$k]=$v;
        }


        if($list){
			$end=end($list);
			$_SESSION['music_video_endtime']=$end['addtime_format'];
		}

		return $list;
    }


    //获取音乐信息
	public function getMusicInfo($musicid){
		$musicinfo=DI()->notorm->user_music->select("title,author,img_url,file_url,use_nums,length")->where("id=? and isdel=0",$musicid)->fetchOne();
		if(!$musicinfo){
			return 1001;
		}

		$musicinfo['img_url']=get_upload_path($musicinfo['img_url']);
		$musicinfo['file_url']=get_upload_path($musicinfo['file_url']);
		$musicinfo['use_nums']=$musicinfo['use_nums'].'人参与';

		return $musicinfo;
	}


 
}
